package com.infocollect.project.grant.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import com.infocollect.common.utils.DateUtils;
import com.infocollect.common.utils.ServletUtils;
import com.infocollect.common.utils.bean.BeanUtils;
import com.infocollect.common.utils.poi.JxExcelUtil;
import com.infocollect.framework.aspectj.lang.annotation.Excel;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.project.grant.domain.*;
import com.infocollect.project.grant.service.IGrGrantService;
import com.infocollect.project.system.domain.SysUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.infocollect.framework.aspectj.lang.annotation.Log;
import com.infocollect.framework.aspectj.lang.enums.BusinessType;
import com.infocollect.project.grant.service.IGrExaminerSceneService;
import com.infocollect.framework.web.controller.BaseController;
import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.common.utils.poi.ExcelUtil;
import com.infocollect.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletResponse;

/**
 * 人员签到Controller
 *
 * @author infocollect
 * @date 2022-05-14
 */
@RestController
@RequestMapping("/grant/examinerscene")
public class GrExaminerSceneController extends BaseController
{
    @Autowired
    private IGrExaminerSceneService grExaminerSceneService;
    @Autowired
    private IGrGrantService grGrantService;

    /**
     * 查询人员签到列表
     */
    @PreAuthorize("@ss.hasPermi('grant:examinerscene:list')")
    @GetMapping("/list")
    public TableDataInfo list(GrExaminerSceneNew grExaminerScene)
    {
        startPage();
        List<GrExaminerSceneNew> list = grExaminerSceneService.selectGrExaminerSceneList(grExaminerScene);
        return getDataTable(list);
    }

    /**
     * 导出人员签到列表
     */
    @PreAuthorize("@ss.hasPermi('grant:examinerscene:export')")
    @Log(title = "人员签到", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GrExaminerSceneNew grExaminerScene)
    {
        List<GrExaminerSceneNew> list = grExaminerSceneService.selectGrExaminerSceneList(grExaminerScene);
        for (GrExaminerSceneNew grExaminerGrant : list) {
            if (grExaminerGrant.getTime()!=null){
                grExaminerGrant.setTimeStr(DateUtils.dateToStrLong(grExaminerGrant.getTime()));
            }

            switch(grExaminerGrant.getStatus()){
                case 1: grExaminerGrant.setStatusStr("正常");break;
                case 2: grExaminerGrant.setStatusStr("迟到");break;
                case 3: grExaminerGrant.setStatusStr("未到");break;
                default: grExaminerGrant.setStatusStr("");break;
            }
        }
        ExcelUtil<GrExaminerSceneNew> util = new ExcelUtil<GrExaminerSceneNew>(GrExaminerSceneNew.class);
        return util.exportExcel(list, "examinerscene");
    }

    /**
     * 获取人员签到详细信息
     */
    @PreAuthorize("@ss.hasPermi('grant:examinerscene:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(grExaminerSceneService.selectGrExaminerSceneById(id));
    }

    /**
     * 新增人员签到
     */
    @PreAuthorize("@ss.hasPermi('grant:examinerscene:add')")
    @Log(title = "人员签到", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GrExaminerScene grExaminerScene)
    {
        return toAjax(grExaminerSceneService.insertGrExaminerScene(grExaminerScene));
    }

    /**
     * 修改人员签到
     */
    @PreAuthorize("@ss.hasPermi('grant:examinerscene:edit')")
    @Log(title = "人员签到", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GrExaminerScene grExaminerScene)
    {
        return toAjax(grExaminerSceneService.updateGrExaminerScene(grExaminerScene));
    }

    /**
     * 删除人员签到
     */
    @PreAuthorize("@ss.hasPermi('grant:examinerscene:remove')")
    @Log(title = "人员签到", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(grExaminerSceneService.deleteGrExaminerSceneByIds(ids));
    }

    @Log(title = "人员签到", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:examinerscene:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Long grantId,String sceneId,Long examinerPointId) throws Exception
    {
        if(grantId==null){
            return AjaxResult.error("上传错误，请选择项目！");
        }

        if(StringUtils.isEmpty(sceneId)){
            return AjaxResult.error("上传错误，请选择场次！");
        }

        Integer dataNumber = 0;
        if(file!=null)
        {
            ExcelUtil<SceneListForPointExcel> util = new ExcelUtil<>(SceneListForPointExcel.class);
            List<SceneListForPointExcel> xsbBeanList = util.importExcel(file.getInputStream());
            for(int ni =xsbBeanList.size()-1; ni>0;ni-- )
            {
                SceneListForPointExcel record = xsbBeanList.get(ni);
                if(StringUtils.isEmpty(record.getIdcard()))
                {
                    xsbBeanList.remove(ni);
                }
            }
            dataNumber = dataNumber + xsbBeanList.size();
            List<SceneListForPointExcel> list1 = grExaminerSceneService.sceneListForPointExcelUpload(xsbBeanList,grantId,sceneId,examinerPointId);
            if (list1 != null && list1.size()>0){
                return AjaxResult.success("数据导入成功"+(dataNumber-list1.size())+"条，失败"+list1.size()+"条，具体请查看excel清单",list1);
            }
        }


        return AjaxResult.success("数据全部导入成功,导入成功数量:"+dataNumber+"条");
    }

    /**
     * 修改考官签到信息
     * @param
     * @return
     */
    @PostMapping("/updateExaminerSceneStatus")
    @ResponseBody
    public AjaxResult updateExaminerSceneStatus(@RequestBody GrExaminerScene grExaminerScene)	{

        Integer i = grExaminerSceneService.updateExaminerSceneStatus(grExaminerScene);

        return AjaxResult.success();
    }


    @GetMapping(value = "/expTemplate")
    public AjaxResult downloadExcelFile(HttpServletResponse response) throws IOException {
        List<GrExaminerSceneTemp> list = new ArrayList<GrExaminerSceneTemp>();
        GrExaminerSceneTemp temp = new GrExaminerSceneTemp();
        temp.setExamMachRoom("1号机房");
        temp.setExaminerName("吴XX");
        temp.setIdCard("3305XXXXXXXXXXX143");
        temp.setExamRoom("2号机房");
        temp.setRoomAddr("2号机房");
        temp.setRemark("1号机房");
        temp.setSignRemark("");
        list.add(temp);

        ExcelUtil<GrExaminerSceneTemp> util = new ExcelUtil<GrExaminerSceneTemp>(GrExaminerSceneTemp.class);
        return util.exportExcel(list, "导入模板");
    }
    @PostMapping("/countExaminerPrice")
    @ResponseBody
    public AjaxResult countExaminerPrice(GrExaminerSceneNew grExaminerScene)
    {
        if(grExaminerScene.getSceneId() ==null || grExaminerScene.getGrantId()==null){
            return AjaxResult.error("参数错误");
        }
        List<GrExaminerSceneNew> list = grExaminerSceneService.selectGrExaminerSceneList(grExaminerScene);
        Long grantId = grExaminerScene.getGrantId();
        GrGrant grGrant = grGrantService.selectGrGrantById(grantId);
        Integer signDay =grGrant.getSignDay();
        Float prefectPrice =  grGrant.getPrefectPrice();
        Float excellentPrice =  grGrant.getExcellentPrice();
        Float examinerPrice =  grGrant.getExaminerPrice();
        Float dutyFreePrice =  grGrant.getDutyFreePrice();
        Float taxRate =  grGrant.getTaxRate();
        for(GrExaminerSceneNew record:list){
            GrExaminerScene examinerScene = new GrExaminerScene();
            examinerScene.setId(record.getId());
            examinerScene.setSignDay(signDay);
            switch (record.getExaminerType())
                {
                case "考官":
                    examinerScene.setDayPrice(examinerPrice);
                    break;
                case "组长":
                    examinerScene.setDayPrice(prefectPrice);
                    break;
                case "优秀":
                    examinerScene.setDayPrice(excellentPrice);
                    break;
            }
            if(examinerScene.getDayPrice()*signDay>=dutyFreePrice){
                examinerScene.setTaxPrice((examinerScene.getDayPrice()*signDay-dutyFreePrice)*taxRate/100);
                examinerScene.setSumPrice(examinerScene.getDayPrice()*signDay-examinerScene.getTaxPrice());
            }else{
                examinerScene.setTaxPrice(0f);
                examinerScene.setSumPrice(examinerScene.getDayPrice()*signDay);
            }
            grExaminerSceneService.updateGrExaminerScene(examinerScene);
        }
        return AjaxResult.success();
    }

}
